package net.hn.hnms.biz.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.project.domain.ProblemRectification;
import net.hn.hnms.biz.project.domain.QualityControlFile;
import net.hn.hnms.biz.project.enums.QualityFileType;
import net.hn.hnms.biz.project.mapper.ProblemRectificationMapper;
import net.hn.hnms.biz.project.mapper.ProjectFileMapper;
import net.hn.hnms.biz.project.mapper.QualityControlFileMapper;
import net.hn.hnms.biz.project.request.ProblemRectificationReq;
import net.hn.hnms.biz.project.service.IProblemRectificationService;
import net.hn.hnms.biz.project.vo.ProblemRectificationVo;
import net.hn.hnms.biz.project.vo.ProjectInfoVo;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.tool.Func;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 刘昊
 * @date 2024-03-13 10:39
 * 问题整改service
 */
@Service
@Slf4j
public class ProblemRectificationServiceImpl implements IProblemRectificationService {

    @Autowired
    private ProblemRectificationMapper rectificationMapper;

    @Autowired
    private QualityControlFileMapper qualityControlFileMapper;


    @Autowired
    private ProjectFileMapper projectFileMapper;


    @Override
    public R<Void> insertReq(ProblemRectificationReq req) {

        ProblemRectification rectificationDO = new ProblemRectification();
        QualityControlFile QualityControlFile = new QualityControlFile();
        try {
            BeanUtils.copyProperties(req,rectificationDO);
            BeanUtils.copyProperties(req,QualityControlFile);
            log.info("问题整改新增========>");
            rectificationMapper.insert(rectificationDO);
            //插入附件
            QualityControlFile.setFileType(QualityFileType.TYPE_2.getValue());
            QualityControlFile.setRelevanceId(rectificationDO.getProblemId());
            log.info("问题整改附件新增========>");
            qualityControlFileMapper.insert(QualityControlFile);
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("新增检查记录失败");
        }
        return R.ok("新增成功");
    }

    @Override
    public R<Void> deleteReq(ProblemRectificationReq req) {
        return null;
    }

    @Override
    public R<Void> updateReq(ProblemRectificationReq req) {
        ProblemRectification rectificationDO = new ProblemRectification();
        QualityControlFile QualityControlFile = new QualityControlFile();
        try {
            BeanUtils.copyProperties(req,rectificationDO);
            BeanUtils.copyProperties(req,QualityControlFile);
            log.info("问题整改修改========>");
            rectificationMapper.updateById(rectificationDO);

            QualityControlFile.setFileType(QualityFileType.TYPE_2.getValue());
            QualityControlFile.setRelevanceId(rectificationDO.getProblemId());
            qualityControlFileMapper.insert(QualityControlFile);
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("修改检查记录失败");
        }
        return R.ok("修改成功");
    }

    @Override
    public R<List<ProblemRectificationVo>> selectList(ProblemRectificationReq req) {
        return null;
    }

    @Override
    public R<Void> deleteList(List<String> idList) {
        try {
            idList.forEach(item -> {
                rectificationMapper.deleteById(item);
                // todo
            });
        }catch (Exception e) {
            log.info("错误信息:{}",e.getMessage());
            return R.fail("删除失败");
        }
        return R.ok("删除成功");
    }

    @Override
    public R<ResponsePage<List<ProblemRectificationVo>>> selectPageList(ProblemRectificationReq req, PageQuery pageQuery) {

//        QueryWrapper<ProblemRectification> recordQueryWrapper = new QueryWrapper<>();
        QueryWrapper<QualityControlFile> qualityControlFileQuerywrapper = new QueryWrapper<>();
        List<ProblemRectificationVo> rectificationVoList = new ArrayList<>();
//        if (StringUtils.isNotBlank(req.getProblemId())) {
//            recordQueryWrapper.eq("problem_id",req.getProblemId());
//        }
//        if (StringUtils.isNotBlank(req.getProjectId())) {
//            recordQueryWrapper.eq("project_id",req.getProjectId());
//        }
//
////        if (StringUtils.isNotBlank(req.getProjectName())) {
////            recordQueryWrapper.eq("project_name",req.getProjectName());
////        }
////        if (StringUtils.isNotBlank(req.getConstructionUnit())) {
////            recordQueryWrapper.eq("construction_unit",req.getConstructionUnit());
////        }
//        if (StringUtils.isNotBlank(req.getMineCode())) {
//            recordQueryWrapper.eq("mine_code",req.getMineCode());
//        }
//        log.info("问题整改查询========>");
//        Page<ProblemRectification> page = rectificationMapper.selectPage(pageQuery.build(),recordQueryWrapper);


        //先查询项目信息（项目名称和施工单位）
//        List<ProjectInfoVo> projectListByCondition = projectFileMapper.getProjectListByCondition(req.getProjectId(), req.getConstructionUnit());
        List<ProjectInfoVo> projectListByCondition = projectFileMapper.getProjectListByCondition_new(req.getProjectId(),req.getProjectName(), req.getConstructionUnit());
        if (Func.isNotEmpty(projectListByCondition)) {
            //提取projectId列表
            List<String> projectIds = projectListByCondition.stream()
                    .map(ProjectInfoVo::getProjectId)
                    .collect(Collectors.toList());
            req.setProjectIds(projectIds);
            Page<ProblemRectification> page = rectificationMapper.selectPage(pageQuery.build(), buildQuery(req).orderByDesc(ProblemRectification::getCreateTime));

            List<ProblemRectificationVo> list = page.getRecords().stream().map(o -> {
                ProblemRectificationVo vo = new ProblemRectificationVo();
                BeanUtil.copyProperties(o, vo);

                // 获取项目名称和施工单位信息
                Optional<ProjectInfoVo> projectInfo = projectListByCondition.stream()
                        .filter(p -> p.getProjectId().equals(o.getProjectId()))
                        .findFirst();

                projectInfo.ifPresent(p -> {
                    vo.setProjectName(p.getProjectName());
                    vo.setConstructionUnit(p.getConstructionUnit());
                });

                return vo;
            }).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(page.getRecords())) {
                for (ProblemRectificationVo rectificationDO :list) {
                    ProblemRectificationVo res = new ProblemRectificationVo();
                    BeanUtils.copyProperties(rectificationDO,res);
                    qualityControlFileQuerywrapper.eq("file_type",QualityFileType.TYPE_2.getValue());
                    if(StringUtils.isNotBlank(rectificationDO.getProblemId())) {
                        qualityControlFileQuerywrapper.eq("relevance_id",rectificationDO.getProblemId());
                    }
                    log.info("问题整改附件查询========>");
                    List<QualityControlFile> fileDOList = qualityControlFileMapper.selectList(qualityControlFileQuerywrapper);
                    res.setQualityControlFileList(fileDOList);
                    rectificationVoList.add(res);
                }
            }
            ResponsePage<List<ProblemRectificationVo>> resultPage = new ResponsePage<>(rectificationVoList,page.getTotal());
            return R.ok("查询完成",resultPage);
        }else{
            ResponsePage<List<ProblemRectificationVo>> resultPage = new ResponsePage<>(rectificationVoList,0);
            return R.ok("查询完成",resultPage);
        }

    }


    private LambdaQueryWrapper<ProblemRectification> buildQuery(ProblemRectificationReq req){
        return new LambdaQueryWrapper<ProblemRectification>()
//                .like(StrUtil.isNotBlank(req.getVehicleCode()), ProblemRectification::getVehicleCode, req.getVehicleCode())
                .in(!org.springframework.util.CollectionUtils.isEmpty(req.getProjectIds()), ProblemRectification::getProjectId, req.getProjectIds())
                .eq(StrUtil.isNotBlank(req.getProjectId()), ProblemRectification::getProjectId, req.getProjectId())
                .eq(StrUtil.isNotBlank(req.getMineCode()), ProblemRectification::getMineCode, req.getMineCode());
    }
}
